package com.quanyue.music.system.service.impl;

import com.quanyue.auto.cache.CacheService;
import com.quanyue.music.domain.constant.ApplyStatus;
import com.quanyue.music.domain.constant.CacheConstants;
import com.quanyue.music.domain.entity.Domain;
import com.quanyue.music.system.mapper.DomainMapper;
import com.quanyue.music.system.service.DomainService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class DomainServiceImpl implements DomainService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private DomainMapper domainMapper;

    @Override
    public String findApprovedDomain(Integer merchantNo) {
        Optional<String> domain = approvedDomainMap()
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue().getMerchantNo().equals(merchantNo))
                .map(Map.Entry::getKey)
                .findAny();
        return domain.orElse(null);
    }

    @Override
    public Domain findByMerchantNo(Integer merchantNo) {
        Optional<Domain> domain = approvedDomainMap()
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue().getMerchantNo().equals(merchantNo))
                .map(Map.Entry::getValue)
                .findAny();
        return domain.orElse(null);
    }

    @Override
    public Integer findMerchantNoByDomain(String domain) {
        Map<String, Domain> test = approvedDomainMap();
        return approvedDomainMap().getOrDefault(domain, new Domain()).getMerchantNo();
    }

    private Map<String, Domain> approvedDomainMap() {
        return cacheService.get(CacheConstants.DOMAIN_CACHE.name());
    }

    @PostConstruct
    public void initCache() {
        Map<String, Domain> domainMap = domainMapper.findByStatus(ApplyStatus.DONE)
                .stream()
                .map(domainItem -> {
                    domainItem.setCompanyName("量子音乐");
                    return domainItem;
                }).collect(Collectors.toMap(Domain::getDomain, d -> d));
        cacheService.put(CacheConstants.DOMAIN_CACHE.name(), domainMap);
    }
}
